package com.qf.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.qf.pojo.Student;
import com.qf.service.StudentService;
import com.qf.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/stu")
public class StudentServlet extends HttpServlet {

    private StudentService studentService = new StudentServiceImpl();

    private ObjectMapper om = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String action = req.getParameter("action");

        if ("findPage".equals(action)){
            findPage(req,resp);
        }
    }

    private void findPage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //接收分页参数
        String pageNumStr = req.getParameter("pageNum");
        String sizeStr = req.getParameter("size");

        int pageNum = 1;
        int size = 2;

        try {
            pageNum = Integer.parseInt(pageNumStr);
        }catch (Exception e){}
        try {
            size = Integer.parseInt(sizeStr);
        }catch (Exception e){}

        //调用service
        PageInfo<Student> pageInfo = studentService.findPage(pageNum, size);

        //响应数据
        String json = om.writeValueAsString(pageInfo);

        resp.getWriter().write(json);
    }
}
